package com.pipayshop.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * JWT 工具类
 */
public class JwtUtil {
    public static void main(String[] args) {
        // 生成符合 HS256 的密钥
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        // 将密钥编码为 Base64
        String base64EncodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        // 输出 Base64 编码的密钥
        System.out.println("Base64 Encoded Key: " + base64EncodedKey);
    }

    // 有效期为 8 小时
    public static final Long JWT_TTL = 8 * 60 * 60 * 1000L;
    // 设置秘钥明文
    public static final String JWT_KEY = "2LSXOL9oLjYMbZ8ZQX/Z2umjDEi/1rtUbwm+HqbzxKA=";

    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成 JWT
     * @param subject token 中要存放的数据（json 格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }

    /**
     * 生成 JWT
     * @param subject token 中要存放的数据（json 格式）
     * @param ttlMillis token 超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("sg")
                .setIssuedAt(now)
                .signWith(secretKey, signatureAlgorithm)
                .setExpiration(expDate);
    }

    /**
     * 生成 HMAC-SHA256 密钥
     * @return
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        return new SecretKeySpec(encodedKey, "HmacSHA256");
    }

    /**
     * 解析 JWT
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(jwt)
                .getBody();
    }
}
